﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TCPUtil
{
    class TcpClientThread
    {
        public static Socket tcpClient;
        public static void InitTcpClient(string IpStr,int prot)
        {
            tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipaddress = IPAddress.Parse(IpStr);
            EndPoint point = new IPEndPoint(ipaddress, prot);
            tcpClient.Connect(point);
        }

        public static void TcpSendMsg(string IpStr, int prot, string data)
        {
            try
            {
                TcpClient tcpClient = new TcpClient();
                var result = tcpClient.BeginConnect(IpStr, prot, null, null);
                var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2f));
                if (!success) return;
                //结束连接
                tcpClient.EndConnect(result);

                NetworkStream ntwstream = tcpClient.GetStream();
                if (ntwstream.CanWrite)
                {
                    byte[] bytesend = Encoding.UTF8.GetBytes(data.Trim());
                    ntwstream.Write(bytesend, 0, bytesend.Length);
                }
                else
                {
                    ntwstream.Close();
                    tcpClient.Close();
                    return;
                }
            }
            catch (Exception)
            {
            }

        }

    }

}
